<?php

namespace Aws;

use Aws\Exception\AwsException;
use Aws\S3\MultipartUploader;
use Aws\S3\S3Client;
use think\Log;

class AwsService
{
    static protected $instance;
    static protected $ak = "AKIARXCTBYE6OBASHQ5Z";
    static protected $sk = "FGCdJQvQnwAzIo77bhnlxtMOwfVd5zc7znZg3AyE";
    static protected $region = "ap-southeast-1"; // 区域:新加坡
    static public $endpoint = "http://s3.ap-southeast-1.amazonaws.com";
    static public $bucket1 = "odrama.tv";
    static public $aws_url1 = 'http://papp.odrama.tv';
    protected $client;

    protected $bucket= "odrama.tv";
    protected $aws_url = 'http://papp.odrama.tv';

    public function __construct()
    {
        $config = [
            'version' => 'latest',
            'region' => self::$region,
            'bucket' => $this->bucket,
            'endpoint'=>self::$endpoint,
            'credentials' => [
                'key' => self::$ak,
                'secret' => self::$sk,
            ],
            'scheme'  => 'http'
        ];

        $this->client = new S3Client($config);
    }

    public static function make()
    {
        if (is_null(self::$instance)) {
            self::$instance = new self(self::$ak, self::$sk, self::$region);
        }
        return self::$instance;
    }
    public function uploadByUrl($path, $url, $bucket = null)
    {
        Log::info('path:' . $path . ',url:' . $url);
        try {
            $bucket = $bucket ? $bucket : $this->bucket;
            $attr = ['Bucket' => $bucket,
                'Key' => trim($path,'/'),
                'Body' => file_get_contents($url)
            ];
            return $this->client->putObject($attr);
        } catch (Exception $e) {
            \think\Log::error($e->getMessage());
            \think\Log::error($e->getTraceAsString());
            return false;
        }
    }
    public function uploadByPath($path, $ext, $bucket = null)
    {
        Log::info('path:' . $path);
        try {
            $key = 'duanju/'.date('Y-m-d') .'/'. uniqid().'.'.$ext;
            $attr = [
                'Bucket' =>  $this->bucket,
                'Key' => $key,
                'SourceFile' => $path,
                'ACL'        => 'public-read' // 可选：设置访问权限
            ];

            return $this->client->putObject($attr);
        } catch (Exception $e) {
            \think\Log::error($e->getMessage());
            \think\Log::error($e->getTraceAsString());
            return false;
        }
    }
    public function createPath($id){
        try {
            // 创建一个零字节的空文件作为目录占位符
            $result = $this->client->putObject([
                'Bucket' => $this->bucket,
                'Key'    => 'duanju/'.$id.'/',
                'Body'   => '' ,// 空字符串，表示零字节数据
                'ACL'    => 'public-read'
            ]);
            return true;
        } catch (S3Exception $e) {
            echo $e->getMessage();
        }
    }


    public function renameS3File($oldPath,$oldName, $newName) {
        try {
            $oldKey = str_replace($this->aws_url.'/', '', $oldPath);
            $len_b = mb_strrpos($oldName, '.');
            $oldName = mb_substr($oldName, 0, $len_b,'UTF-8');
            $newKey = str_replace($oldName,$newName,$oldKey);
            // 复制文件到新名称
//            var_dump([
//                'oldKey'=>$oldKey,
//                'oldName'=>$oldName,
//                'newName'=>$newName,
//                'Bucket'     => $this->bucket,
//                'CopySource' => "{$this->bucket}/{$oldKey}",
//                'Key'        => "{$newKey}"
//            ]);
             $this->client->copyObject([
                'Bucket'     => $this->bucket,
                'CopySource' => rawurlencode("{$this->bucket}/{$oldKey}"),
                'Key'        => "{$newKey}"
            ]);

//            // 删除原文件
//            $this->client->deleteObject([
//                'Bucket' => $this->bucket,
//                'Key'    => $oldKey
//            ]);
            return true;

        } catch (AwsException $e) {
            echo "错误: " . $e->getMessage();
            return false;
        }
    }

    /**
     * 获取存储桶指定key下的文件列表，排除已有的文件
     * @param $id
     * @return array|void
     */
    public function getFilesByPath($id){
        $s3 =$this->client ;
        try {
            $aws_url = 'http://papp.odrama.tv';
            $bucket = 'odrama.tv'; // 你的存储桶名称
            $prefix = 'duanju/'.$id.'/'; // 可选，用于过滤对象的前缀
            $result = $s3->listObjects([
                'Bucket' => $bucket,
                'Prefix' => $prefix,
            ]);
            $objects = $result['Contents']; // 获取对象列表
//            while ($result['IsTruncated'] == 'true') { // 检查是否还有更多结果需要获取
//                $nextToken = $result['NextContinuationToken']; // 获取下一页的令牌
//                $result = $s3->listObjectsV2([
//                    'Bucket' => $bucket,
//                    'Prefix' => $prefix,
//                    'ContinuationToken' => $nextToken, // 使用令牌继续获取下一页结果
//                ]);
//                $objects = array_merge($objects, $result['Contents']); // 合并结果集
//            }
            $files = [];
            foreach ($objects as $object) {
//                $r = $s3->putBucketAcl([
//                    'Bucket' => $bucket,
//                    'Key'    => $object['Key'],
//                    'ACL'    => 'public-read'
//                ]);
                if($object['Size'] > 0){
                    $files[] = $aws_url.'/'.$object['Key'];
                }
            }
            return $files;
        } catch (AwsException $e) {
            // 输出错误信息
            echo $e->getMessage();
        }
    }
    public function uploadPartByPath($path, $ext, $bucket = null)
    {
        $S3 = new S3Client([
            'version'     => 'latest',
            'region' => 'nl-ams-1',
            'credentials' => [
                'key' => "EI3XKRRMNXZ7FN883PIO",
                'secret' => "XlVbeGsMdVa6CxO7M0mfU1qqkfXfYivcRPu2Y5Dk",
            ],
            'scheme'  => 'http'
        ]);
        $bucket ='assets.xescort.net';// $bucket ? $bucket : $this->bucket;
        $key = 'duanju/'.date('Y-m-d') .'/'. uniqid().'.'.$ext;
            $filePath = $path; // 例如 '/path/to/your/file.txt'

          // try {
        $uploader = new MultipartUploader($S3, $path, [
            'bucket' => $bucket,
            'key' => $key,
        ]);

        try {
            $result = $uploader->upload();
            echo "Upload complete: {$result['ObjectURL']}\n";
        } catch (MultipartUploadException $e) {
            echo $e->getMessage() . "\n";
        }
                echo "上传成功\n";
                print_r($result);
//            } catch (AwsException $e) {
//                echo "上传失败: " . $e->getMessage() . "\n";
//            }
//           finally {
//                if (isset($fileParts['Body'])) {
//                    fclose($fileParts['Body']); // 关闭文件流资源，以防内存泄漏或其他问题。
//                }
//            }


    }

}